﻿using NPOI.XWPF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Text;


namespace System
{
  public  class ReplaceWordText
    {
        /// <summary>
        /// 读取Word内容
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string ReadWordText(string fileName)
        {
            string WordTableCellSeparator = "true";// ConfigurationManager.AppSettings["WordTableCellSeparator"];
            string WordTableRowSeparator = "true";//ConfigurationManager.AppSettings["WordTableRowSeparator"];
            string WordTableSeparator = "true";//ConfigurationManager.AppSettings["WordTableSeparator"];
            //
            string CaptureWordHeader = "true";//ConfigurationManager.AppSettings["CaptureWordHeader"];
            string CaptureWordFooter = "true";//ConfigurationManager.AppSettings["CaptureWordFooter"];
            string CaptureWordTable = "true";//ConfigurationManager.AppSettings["CaptureWordTable"];
            string CaptureWordImage = "true";//ConfigurationManager.AppSettings["CaptureWordImage"];
            //
            string CaptureWordImageFileName = "true";// ConfigurationManager.AppSettings["CaptureWordImageFileName"];
            //
            string fileText = string.Empty;
            StringBuilder sbFileText = new StringBuilder();

            #region 打开文档
            XWPFDocument document = null;
            try
            {
                using (FileStream file = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    document = new XWPFDocument(file);
                }
            }
            catch (Exception)
            {
               // LogHandler.LogWrite(string.Format("文件{0}打开失败，错误：{1}", new string[] { fileName, e.ToString() }));
            }
            #endregion

            #region 页眉、页脚
            //页眉
            if (CaptureWordHeader == "true")
            {
                sbFileText.AppendLine("Capture Header Begin");
                foreach (XWPFHeader xwpfHeader in document.HeaderList)
                {
                    sbFileText.AppendLine(string.Format("{0}", new string[] { xwpfHeader.Text }));
                }
                sbFileText.AppendLine("Capture Header End");
            }
            //页脚
            if (CaptureWordFooter == "true")
            {
                sbFileText.AppendLine("Capture Footer Begin");
                foreach (XWPFFooter xwpfFooter in document.FooterList)
                {
                    sbFileText.AppendLine(string.Format("{0}", new string[] { xwpfFooter.Text }));
                }
                sbFileText.AppendLine("Capture Footer End");
            }
            #endregion

            #region 表格
            if (CaptureWordTable == "true")
            {
                sbFileText.AppendLine("Capture Table Begin");
                foreach (XWPFTable table in document.Tables)
                {
                    //循环表格行
                    foreach (XWPFTableRow row in table.Rows)
                    {
                        foreach (XWPFTableCell cell in row.GetTableCells())
                        {
                            sbFileText.Append(cell.GetText());
                            //
                            sbFileText.Append(WordTableCellSeparator);
                        }

                        sbFileText.Append(WordTableRowSeparator);
                    }
                    sbFileText.Append(WordTableSeparator);
                }
                sbFileText.AppendLine("Capture Table End");
            }
            #endregion

            #region 图片
            if (CaptureWordImage == "true")
            {
                sbFileText.AppendLine("Capture Image Begin");
                foreach (XWPFPictureData pictureData in document.AllPictures)
                {
                    string picExtName = pictureData.SuggestFileExtension();
                    string picFileName = pictureData.FileName;
                    byte[] picFileContent = pictureData.Data;
                    //
                    string picTempName = string.Format(CaptureWordImageFileName, new string[] { Guid.NewGuid().ToString() + "_" + picFileName + "." + picExtName });
                    //
                    using (FileStream fs = new FileStream(picTempName, FileMode.Create, FileAccess.Write))
                    {
                        fs.Write(picFileContent, 0, picFileContent.Length);
                        fs.Close();
                    }
                    //
                    sbFileText.AppendLine(picTempName);
                }
                sbFileText.AppendLine("Capture Image End");
            }
            #endregion

            //正文段落
            sbFileText.AppendLine("Capture Paragraph Begin");
            foreach (XWPFParagraph paragraph in document.Paragraphs)
            {
                sbFileText.AppendLine(paragraph.ParagraphText);

            }
            sbFileText.AppendLine("Capture Paragraph End");
            //

            //
            fileText = sbFileText.ToString();
            return fileText;
        }

        /// <summary>
        /// 替换word内容
        /// </summary>
        /// <param name="pathfile">模版文件地址</param>
        /// <param name="fileName">新生成文件地址</param>
        /// <param name="oldstr">原字符</param>
        /// <param name="newstr">替换后字符</param>
        public static void ReplacWord(string pathfile, string fileName, string[] oldstr, string[] newstr)
        { 
            MemoryStream stream = Export(pathfile, oldstr, newstr);
            FileStream fs = new FileStream(fileName, FileMode.Create);
            byte[] buff = stream.ToArray();
            fs.Write(buff, 0, buff.Length);
            fs.Close();
        }

        private static MemoryStream Export(string pathfile, string[] oldstr, string[] newstr)
        {

            string filepath = pathfile;// Server.MapPath("/word/xmxx.docx");
            using (FileStream stream = File.OpenRead(filepath))
            {
                XWPFDocument doc = new XWPFDocument(stream);
                //遍历段落
                foreach (var para in doc.Paragraphs)
                {
                    ReplaceKey(para, oldstr, newstr);
                }
                //遍历表格
                var tables = doc.Tables;
                foreach (var table in tables)
                {
                    foreach (var row in table.Rows)
                    {
                        foreach (var cell in row.GetTableCells())
                        {
                            foreach (var para in cell.Paragraphs)
                            {
                                ReplaceKey(para, oldstr, newstr);
                            }
                        }
                    }
                }

                //using (MemoryStream ms = new MemoryStream())
                //{
                MemoryStream ms = new MemoryStream();
                doc.Write(ms);
                return ms;
                //}                
            }
        }

        private static void ReplaceKey(XWPFParagraph para, string[] oldstr, string[] newstr)
        {

            string text = para.ParagraphText;
            var runs = para.Runs;
           // string styleid = para.Style;
            for (int i = 0; i < runs.Count; i++)
            {

                var run = runs[i];
                text = run.ToString();
                //Type t = para.GetType();
                //PropertyInfo[] pi = t.GetProperties();
                //foreach (PropertyInfo p in pi)
                //{
                    for (int k = 0; k < oldstr.Length; k++)
                    {
                        text = text.Replace( oldstr[k], newstr[k]);
                    }
                //}
                runs[i].SetText(text);
            }
        }



    }
}
